﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Windows.Forms;

namespace LUC
{
	public static class Serializator
	{
		public static T LoadModel<T>(this T model)
		{
			using (OpenFileDialog od = new OpenFileDialog())
			{
				if (od.ShowDialog() != DialogResult.OK)
					return model;
				return FromFileToModel<T>(od.FileName);
			}
		}
		public static T LoadModel<T>(this T model, string file_ext, string title) where T : class
		{
			try
			{
				using (OpenFileDialog od = new OpenFileDialog())
				{
					od.Filter = file_ext + " files" + "|*." + file_ext;
					od.DefaultExt = file_ext;
					od.Title = title;
					if (od.ShowDialog() != DialogResult.OK)
						return null;
					return FromFileToModel<T>(od.FileName);
				}
			}
			catch
			{
				MessageBox.Show("Wrong file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return null;
			}
		}
		public static T FromFileToModel<T>(string filename)
		{
			StreamReader sr = new StreamReader(filename);
			T t = FromStreamToModel<T>(sr.BaseStream);
			sr.Close();
			return t;
		}
		public static T FromBytesToModel<T>(this byte[] data) where T:class, new()
		{
			var stream = new MemoryStream(data);
			stream.Flush();
			stream.Position = 0;
			return (T)FromStreamToModel<T>(stream);
		}
		public static T FromStreamToModel<T>(Stream stream)
		{
			XmlSerializer xs = new XmlSerializer(typeof(T));
			return (T)xs.Deserialize(stream);
		}

		public static void SaveModel<T>(this T model)
		{
			using (SaveFileDialog sd = new SaveFileDialog())
			{
				if (sd.ShowDialog() != DialogResult.OK)
					return;
				ModelToFile<T>(model, sd.FileName);
			}
		}
		public static void SaveModel<T>(this T model, string file_ext, string title)
		{
			using (SaveFileDialog sd = new SaveFileDialog())
			{
				sd.Filter = file_ext + " files" + "|*." + file_ext;
				sd.DefaultExt = file_ext;
				sd.Title = title;
				if (sd.ShowDialog() != DialogResult.OK)
					return;
				ModelToFile<T>(model, sd.FileName);
			}
		}
		public static void ModelToFile<T>(this T model, string filename)
		{
			FileStream fs = new FileStream(filename, FileMode.Create);
			new XmlSerializer(typeof(T)).Serialize(fs, model);
			fs.Flush();
			fs.Close();
		}
		public static byte[] ModelToBytes<T>(this T model)
		{
			MemoryStream stream = ModelToStream<T>(model);
			return stream.ToArray();
		}
		public static MemoryStream ModelToStream<T>(this T model)
		{
			MemoryStream stream = new MemoryStream();
			var xs = new XmlSerializer(typeof(T));
			xs.Serialize(stream, model);
			stream.Flush();
			stream.Position = 0;
			return stream;
		}
	}
}
